__author__ = 'tyrion'

import commands
import numpy as np
import  re
import json

def GetData(rrdFile , startTime , endTime ):
    # result = ""

    # filePath = "/usr/local/pnp4nagios/var/perfdata/%s/%s" % ()
    cmd = "rrdtool fetch /usr/local/pnp4nagios/var/perfdata/172.24.133.117/CPU_load.rrd  AVERAGE "
    result = commands.getoutput(cmd)

    return result



def GetHistoryPerfData(instanceName, svrName, startTime, endTime, step):

    cmd = "rrdtool  fetch /usr/local/pnp4nagios/var/perfdata/%s/%s.rrd   AVERAGE -s %s  -e %s"%(svrName, instanceName, startTime, endTime)
    print("info:%s" %cmd)
    ret = commands.getoutput(cmd)
    print(ret)

    sList  = re.sub("-nan", "0", ret).split('\n')[2:]
    print sList
    statTime = sList[0].split(':')[0]
    print(statTime)

    tList = []
    for ele in sList:
        tmpList = ele.split(':')
        try:
            tmpList2 = tmpList[1].strip(' ').split(' ')
            tList.append(tmpList2)
        except IndexError:
            return "error : please check the server name and instance name"

    print(tList)
    floatTList =  [[ float(x) for x in inner] for inner in tList]
    print(floatTList)
    realStep = int(int(step)/60)
    print floatTList.__len__()
    print(len(floatTList))

    lastRet = []
    num = int(len(floatTList)/realStep)
    print( num)
    for i in range( 0,  num+1 , realStep):
        tmparray = np.array(floatTList[i:i+realStep])
        # print(tmparray)
        # print(tmparray.mean(axis=0))
        lastRet.append(tmparray.mean(axis=0).tolist())

    jsonRet = json.dumps(lastRet)
    # jsonRet = json.dumps(tmparray.mean(axis=0).tolist())
    return  jsonRet

if __name__ == "__main__":
    GetData()